package com.yvon.maple.cloud.web.filter;

import cn.hutool.core.util.StrUtil;
import com.yvon.maple.cloud.web.properties.FeignInsideProperties;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import static com.yvon.maple.constants.SystemConstant.Common.STR_LOGIN_USER;

/**
 * feign请求拦截器
 *
 * @author : Yvon
 * @since : 2022-03-17
 */
public class FeignRequestInterceptor implements RequestInterceptor {
    @Resource
    private FeignInsideProperties feignInsideProperties;

    @Override
    public void apply(RequestTemplate requestTemplate) {
        // 获取当前请求Spring信息
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        // 获取请求体
        if (null != attributes) {
            HttpServletRequest request = attributes.getRequest();
            // 获取Header、或参数等
            String loginUser = request.getHeader(STR_LOGIN_USER);
            // 注入Feign请求体
            requestTemplate.header(STR_LOGIN_USER, loginUser);
            requestTemplate.header(feignInsideProperties.getKey(), feignInsideProperties.getSecret());
        }
    }

}

